package cn.elwy.rcp.ui.table.internal;

import java.util.Timer;
import java.util.TimerTask;

import org.eclipse.swt.widgets.Display;

import cn.elwy.rcp.ui.table.TablePane;
import cn.elwy.rcp.ui.table.model.TableInfo;

public class TablePaneRefreshSupport {

  private final TablePane tablePane;
  private final TableInfo tableInfo;
  private Timer timer;
  private TimerTask task;

  public TablePaneRefreshSupport(TablePane tablePane, TableInfo tableInfo) {
    this.tablePane = tablePane;
    this.tableInfo = tableInfo;
  }

  public void createTimer() {
    if (tableInfo.isAutoRefresh() == false || tableInfo.getDefaultRefreshInterval() <= 0) {
      return;
    }

    task = getTimeTask();
    timer = new Timer();
    schedule(timer, task);

  }

  private TimerTask getTimeTask() {
    return new TimerTask() {
      @Override
      public void run() {
        Display.getDefault().asyncExec(new Runnable() {

          @Override
          public void run() {
            if (tablePane.isDisposed() || tableInfo.getDefaultRefreshInterval() <= 0) {
              cancel();
              return;
            }
            tablePane.refresh();
          }
        });
      }
    };
  }

  public void setRefreshInterval(int interval) {
    cancelTimer();
    tableInfo.setDefaultRefreshInterval(interval);
    createTimer();
  }

  private void schedule(Timer timer, TimerTask task) {
    int period = tableInfo.getDefaultRefreshInterval() * 1000;
    timer.schedule(task, period, period);
  }

  private void cancelTimer() {
    try {
      if (timer != null) {
        timer.cancel();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void dispose() {
    cancelTimer();
  }

}
